<script setup lang="tsx">
import { ContentWrap } from '@/components/ContentWrap'
import { Search } from '@/components/Search'
import { Dialog } from '@/components/Dialog'
import { useI18n } from '@/hooks/web/useI18n'
import { Table } from '@/components/Table'
import { useTable } from '@/hooks/web/useTable'
import { ref, unref, reactive, h } from 'vue'
import { CrudSchema, useCrudSchemas } from '@/hooks/web/useCrudSchemas'
import { BaseButton } from '@/components/Button'
import { ElMessage, ElTag } from 'element-plus'
import SetSecurCheckApi from '@/api/securcheck/SetSecurCheck'
import { useDictStore } from '@/store/modules/dictData'
import { GroupListType } from '@/api/securcheck/type'
import { useSecurCheckStore } from '@/store/modules/securcheck'
import Write from '../../TransferComponent/Write.vue'
import NotSelected from '../../TransferComponent/NotSelected.vue'
const ids = ref<string[]>([])
const SecurCheckStore = useSecurCheckStore()
const { tableRegister, tableState, tableMethods } = useTable({
  fetchDataApi: async () => {
    const { currentPage, pageSize } = tableState
    const res = await SetSecurCheckApi.GetGroupList({
      pageNum: unref(currentPage),
      pageSize: unref(pageSize),
      groupUserCom: 0,
      ...unref(searchParams)
    })
    SecurCheckStore.setUserGroupId(res.rows[0].id)
    return {
      list: res.rows,
      total: res.total
    }
  },
  fetchDelApi: async () => {
    const res = await SetSecurCheckApi.DeletGroupList(unref(ids)[0])
    return !!res
  }
})
const DictStore = useDictStore()
//获取字典
DictStore.setDict('secur_group_type') //类型
const { loading, dataList, total, currentPage, pageSize } = tableState
const { getList, getElTableExpose, delList } = tableMethods

const { t } = useI18n()
const crudSchemas = reactive<CrudSchema[]>([
  {
    field: 'index',
    label: t('tableDemo.index'),
    type: 'index',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    }
  },

  {
    field: 'groupName',
    label: t('用户组名称'),
    search: {
      hidden: false,
      component: 'Input',
      componentProps: {
        placeholder: '用户组名称'
      }
    },
    form: {
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'groupType',
    label: t('组类型'),
    search: {
      hidden: true
    },
    formatter: (_: Recordable, __: any, cellValue: string) => {
      return DictStore.$state.secur_group_type?.map((item) => {
        if (item.dictValue == cellValue) {
          return item.dictLabel
        }
      })
    },
    form: {
      component: 'Select',
      componentProps: {
        options: DictStore.$state.secur_group_type?.map((item) => {
          return {
            label: item.dictLabel,
            value: item.dictValue
          }
        })
      },
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'taskCount',
    label: t('关联用户数量'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },

  {
    field: 'groupState',
    label: t('组状态'),
    search: {
      hidden: false,
      component: 'RadioButton',
      value: '',
      componentProps: {
        options: [
          {
            label: '全部',
            value: ''
          },
          {
            label: '停用',
            value: 0
          },
          {
            label: '在用',
            value: 1
          }
        ]
      }
    },
    formatter: (_: Recordable, __: any, cellValue: number) => {
      if (cellValue == 0) {
        return h(ElTag, { type: 'danger' }, () => t('停用'))
      } else if (cellValue == 1) {
        return h(ElTag, { type: 'primary' }, () => t('在用'))
      }
    },

    form: {
      component: 'Switch',
      componentProps: {
        activeValue: 1,
        activeText: '在用',
        inactiveValue: 0,
        inactiveText: '停用'
      },
      colProps: {
        span: 24
      }
    }
  },
  {
    field: 'createBy',
    label: t('创建人'),
    search: {
      hidden: true
    },
    form: {
      hidden: true
    }
  },

  {
    field: 'action',
    label: t('tableDemo.action'),
    width: 170,
    fixed: 'right',
    search: {
      hidden: true
    },
    form: {
      hidden: true
    },
    detail: {
      hidden: true
    },
    table: {
      slots: {
        default: (data: any) => {
          return (
            <>
              <span class="TableBtn color-[#409eff]" onClick={() => action(data.row, 'user')}>
                {t('相关用户')}
              </span>
              <span class="TableBtn color-[#409eff]" onClick={() => action(data.row, 'edit')}>
                {t('修改')}
              </span>
              <span
                onClick={() => SetState(data.row.id, data.row.groupState == 0 ? 1 : 0)}
                class={data.row.groupState == 1 ? 'CloseBtn' : 'OpenBtn'}
              >
                {data.row.groupState == 1 ? '停用' : '启用'}
              </span>
              <span class="TableBtn" style="color:#f56c6c" onClick={() => delData(data.row)}>
                {t('删除')}
              </span>
            </>
          )
        }
      }
    }
  }
])
const currentRow = ref<GroupListType>({})
const saveLoading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('添加')
const actionType = ref('')
const UserGroupWriteRef = ref()
//修改提交
const save = async () => {
  const write = unref(UserGroupWriteRef)
  const formData = await write?.submit()
  if (formData) {
    formData['groupUserCom'] = 0
    saveLoading.value = true
    saveLoading.value = false
    const res: any = ref(false)
    // 新增
    if (actionType.value == 'add') {
      res.value = await SetSecurCheckApi.AddGroupList(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    } else {
      //修改
      res.value = await SetSecurCheckApi.EditGroupList(formData)
        .catch(() => {})
        .finally(() => {
          saveLoading.value = false
        })
    }
    if (res.value) {
      dialogVisible.value = false
      currentPage.value = 1
      getList()
    }
  }
}
//表格操作
const action = async (row: GroupListType, type: string) => {
  actionType.value = type
  currentRow.value = row
  if (type == 'edit' || type == 'add') {
    dialogTitle.value = type == 'edit' ? '修改' : '增加'
    dialogVisible.value = true //打开弹窗
  } else if (type == 'user') {
    SecurCheckStore.setgroupUserCom(0)
    ListVisible.value = true //打开弹窗
  }
}
//修改状态
const SetState = async (id: number, status: number) => {
  const i = await SetSecurCheckApi.EditGroupList({ id: id, groupState: status })
  if (i) {
    getList()
    ElMessage({
      message: status == 1 ? '启用成功' : '停用成功',
      type: 'success'
    })
  }
}
// @ts-ignore
const { allSchemas } = useCrudSchemas(crudSchemas)

const delLoading = ref(false)
//删除
const delData = async (row: GroupListType | null) => {
  const elTableExpose = await getElTableExpose()
  ids.value = row
    ? [row.id]
    : elTableExpose?.getSelectionRows().map((v: GroupListType) => v.id) || []
  delLoading.value = true
  await delList(unref(ids).length).finally(() => {
    delLoading.value = false
  })
}

//高亮选中
const handleCurrentChange = async (currentRow: GroupListType) => {
  SecurCheckStore.setUserGroupId(currentRow.id)
}
const searchParams = ref({})
const setSearchParams = (params: any) => {
  searchParams.value = params
  getList()
}
const ListVisible = ref(false)
const Listsave = () => {
  getList()
  SecurCheckStore.setUserGroupId(0)
  ListVisible.value = false
}
</script>

<template>
  <ContentWrap style="position: relative" :title="t('用户组列表')">
    <BaseButton type="primary" size="small" @click="action({}, 'add')" class="AddbtnStyle">
      <Icon icon="ep:plus" :size="12" />新增
    </BaseButton>
    <Search :schema="allSchemas.searchSchema" @search="setSearchParams" @reset="setSearchParams" />
    <Table
      v-model:pageSize="pageSize"
      v-model:currentPage="currentPage"
      :highlight-current-row="true"
      :columns="allSchemas.tableColumns"
      :data="dataList"
      :loading="loading"
      :pagination="{
        total: total
      }"
      @register="tableRegister"
      @current-change="handleCurrentChange"
    />
    <Dialog v-model="dialogVisible" :title="dialogTitle" class="MeterStyle" maxHeight="200px">
      <Write
        ref="UserGroupWriteRef"
        :current-row="currentRow"
        :form-schema="allSchemas.formSchema"
      />
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="save">
          {{ t('提交') }}
        </BaseButton>
        <BaseButton @click="dialogVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
    <Dialog
      v-model="ListVisible"
      title="添加用户组用户"
      maxHeight="500px"
      style="width: 90% !important"
    >
      <NotSelected :taskId="currentRow.id" />
      <template #footer>
        <BaseButton type="primary" :loading="saveLoading" @click="Listsave">
          {{ t('确定') }}
        </BaseButton>
        <BaseButton @click="ListVisible = false">{{ t('关闭') }}</BaseButton>
      </template>
    </Dialog>
  </ContentWrap>
</template>
<style scoped>
:deep(.MeterStyle) {
  margin-top: -250px !important;
}

:deep(.el-dialog) {
  width: 700px !important;
}
:deep(.CloseBtn) {
  cursor: pointer;
  font-weight: 600;
  margin: 0 3px;
  color: darkgrey;
}
:deep(.OpenBtn) {
  cursor: pointer;
  font-weight: 600;
  margin: 0 3px;
  color: #67c23a;
}
.AddbtnStyle {
  margin-bottom: 16px;
  margin-right: 10px;
}
</style>
